const API_BASE_URL = 'https://ovoav.com/api/sky/sgwz';
const API_KEY = 'ez2yBl9AzXMCN';
const CN_API_URL = 'https://api.xbsky.top/height.php';
const CN_API_KEY = 'b8fcce2d5513858';
const BUCKET = 'sky-1319850798';
const REGION = 'ap-nanjing';
const ANNOUNCEMENT_FILE = 'announcement.json';

let currentServer = 'cn';
let isQuerying = false;
let pendingQueryData = null;
let cosHandler;

function formatResult(data) {
    if (!data) {
        console.error('formatResult: 数据为空');
        return '暂无数据';
    }
    
    try {
        console.log('格式化数据:', data);
        
        if (data.code !== 200) {
            console.error('formatResult: 数据格式错误', data);
            return `<div class="result-content">
                <h3>查询结果</h3>
                <p><span>状态</span><span>数据格式错误</span></p>
                <p><span>错误信息</span><span>${data.msg || '未知错误'}</span></p>
            </div>`;
        }

        let result;
        // 处理国服和国际服/测试服的不同数据格式
        if (data.data && typeof data.data === 'object') {
            // 新的国服数据格式
            result = {
                scale: data.data.scale,
                currentHeight: data.data.currentHeight,
                maxHeight: data.data.maxHeight,
                minHeight: data.data.minHeight
            };
            
            let html = '<div class="result-content">';
            html += `<h3>身高数据</h3>`;
            html += `<p><span>原ID</span><span>${data.uid || '-'}</span></p>`;
            html += `<p><span>好友码</span><span>${data.name || '-'}</span></p>`;
            html += `<p><span>体型值</span><span>${result.scale || '-'}</span></p>`;
            html += `<p><span>当前身高</span><span>${result.currentHeight ? result.currentHeight + 'cm' : '-'}</span></p>`;
            html += `<p><span>最高记录</span><span>${result.maxHeight ? result.maxHeight + 'cm' : '-'}</span></p>`;
            html += `<p><span>最矮记录</span><span>${result.minHeight ? result.minHeight + 'cm' : '-'}</span></p>`;
            
            // 添加装扮信息
            if (data.remote) {
                html += `<h3>装扮信息</h3>`;
                for (const [key, value] of Object.entries(data.remote)) {
                    const label = {
                        wing: '斗篷',
                        prop: '背饰',
                        neck: '项链',
                        mask: '面具',
                        horn: '头饰',
                        hat: '发饰',
                        hair: '发型',
                        feet: '鞋子',
                        face: '面饰',
                        body: '裤子'
                    }[key] || key;
                    html += `<p><span>${label}</span><span>${value}</span></p>`;
                }
            }
            
            html += '</div>';
            return html;
        } else {
            // 国际服/测试服数据格式
            result = data;
            let html = '<div class="result-content">';
            html += `<h3>身高数据</h3>`;
            html += `<p><span>体型值</span><span>${result.scale ?? '-'}</span></p>`;
            html += `<p><span>当前身高</span><span>${result.currentHeight ? result.currentHeight + 'cm' : '-'}</span></p>`;
            html += `<p><span>最高记录</span><span>${result.maxHeight ? result.maxHeight + 'cm' : '-'}</span></p>`;
            html += `<p><span>最矮记录</span><span>${result.minHeight ? result.minHeight + 'cm' : '-'}</span></p>`;
            html += '</div>';
            return html;
        }
    } catch (error) {
        console.error('格式化结果时出错:', error);
        return `<div class="result-content">
            <h3>查询结果</h3>
            <p><span>状态</span><span>处理出错</span></p>
            <p><span>错误信息</span><span>${error.message}</span></p>
        </div>`;
    }
}

function showSnackbar(message) {
    const snackbar = document.getElementById('snackbar');
    snackbar.textContent = message;
    snackbar.classList.add('show');
    setTimeout(() => {
        snackbar.classList.remove('show');
    }, 3000);
}

function showPopup(scale, height) {
    const popup = document.getElementById('resultPopup');
    document.getElementById('resultValue').textContent = scale || '-';
    document.getElementById('currentHeight').textContent = height ? height + 'cm' : '-';
    popup.classList.add('show');
}

function closePopup() {
    const popup = document.getElementById('resultPopup');
    popup.classList.remove('show');
}

async function loadAnnouncement() {
    try {
        const announcement = await cosHandler.getAnnouncement();
        if (announcement) {
            const announcementElement = document.getElementById('announcement');
            if (announcementElement) {
                announcementElement.innerHTML = `
                    <h2 class="announcement-title">公告</h2>
                    <div class="announcement-content">${announcement}</div>
                `;
            }
        }
    } catch (error) {
        console.error('加载公告失败:', error);
    }
}

async function queryHeight() {
    if (isQuerying || !cosHandler) return;

    const userId = document.getElementById('userId').value.trim();
    const longId = document.getElementById('longid').value.trim();
    
    if (!userId) {
        showSnackbar('请输入用户ID');
        return;
    }

    if (!longId) {
        showSnackbar('请输入光遇账号ID');
        return;
    }

    await performQuery(userId, currentServer, longId);
}

async function saveHistory(historyData) {
    try {
        // 获取现有历史记录
        const historyResponse = await cosHandler.getObject('query_history.json');
        let history = [];
        
        try {
            if (historyResponse && historyResponse.Body) {
                history = JSON.parse(historyResponse.Body);
                if (!Array.isArray(history)) {
                    history = [];
                }
            }
        } catch (error) {
            console.error('解析历史记录失败:', error);
            history = [];
        }

        // 添加新记录到开头
        history.unshift(historyData);

        // 限制历史记录数量
        if (history.length > 1000) {
            history = history.slice(0, 1000);
        }

        // 保存更新后的历史记录
        await cosHandler.putObject({
            Bucket: BUCKET,
            Region: REGION,
            Key: 'query_history.json',
            Body: JSON.stringify(history, null, 2),
            ContentType: 'application/json',
            Headers: {
                'Cache-Control': 'no-cache'
            }
        });
    } catch (error) {
        console.error('保存历史记录失败:', error);
    }
}

function formatUserId(userId) {
    if (!userId) return '-';
    if (userId.length > 12) {
        return userId.slice(0, 6) + '...' + userId.slice(-6);
    }
    return userId;
}

function formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;

    if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    }

    if (diff < 7 * 24 * 60 * 60 * 1000) {
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        return days === 0 ? '今天' : `${days}天前`;
    }

    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function renderHistoryItem(item) {
    const formattedTime = formatTimestamp(item.timestamp);
    const serverType = {
        'cn': '国服',
        'live': '国际服',
        'beta': '测试服'
    }[item.type] || item.type;

    const formattedId = formatUserId(item.id);
    const queryUser = formatUserId(item.queryUserId);

    return `
        <div class="history-item" onclick="showHistoryDetail('${JSON.stringify(item.data).replace(/'/g, "\\'")}')">
            <div class="history-item-header">
                <div class="history-item-id">${formattedId}</div>
                <div class="history-item-time">${formattedTime}</div>
            </div>
            <div class="history-item-details">
                <div>查询者: ${queryUser}</div>
                ${item.data.data ? `身高: ${item.data.data.currentHeight}cm` : ''}
            </div>
            <div class="history-item-server">${serverType}</div>
        </div>
    `;
}

async function validateUser(userId) {
    try {
        const userData = await cosHandler.getObject('用户.json');
        if (!userData || !userData.Body) {
            throw new Error('用户数据为空');
        }
        const users = JSON.parse(userData.Body);
        const user = users[userId];
        if (!user) {
            showSnackbar('用户ID不存在');
            return null;
        }
        return user;
    } catch (error) {
        console.error('验证用户失败:', error);
        showSnackbar('验证用户失败');
        return null;
    }
}

function updateUserInfo(user) {
    if (!user) return;
    showSnackbar(`剩余次数: ${user.times || 0}`);
}

async function deductUserTimes(userId) {
    try {
        const response = await cosHandler.getObject('用户.json');
        if (!response || !response.Body) {
            throw new Error('用户数据为空');
        }

        const users = JSON.parse(response.Body);
        const userInfo = users[userId];

        if (!userInfo) {
            throw new Error('用户不存在');
        }

        if (userInfo.times <= 0) {
            throw new Error('剩余次数不足');
        }

        userInfo.times--;
        
        await cosHandler.putObject({
            Bucket: BUCKET,
            Region: REGION,
            Key: '用户.json',
            Body: JSON.stringify(users, null, 2),
            ContentType: 'application/json',
            Headers: {
                'Cache-Control': 'no-cache'
            }
        });

        return userInfo.times;
    } catch (error) {
        console.error('扣除次数失败:', error);
        throw error;
    }
}

async function loadUserInfo(userId) {
    try {
        const response = await cosHandler.getObject('用户.json');
        if (!response || !response.Body) {
            throw new Error('用户数据为空');
        }

        const users = JSON.parse(response.Body) || {};
        const userInfo = users[userId];

        const userInfoElement = document.getElementById('userInfo');
        if (userInfo) {
            document.getElementById('remainingTimes').textContent = userInfo.times || 0;
            userInfoElement.style.display = 'flex';
            setTimeout(() => userInfoElement.classList.add('show'), 50);
        } else {
            userInfoElement.classList.remove('show');
            setTimeout(() => userInfoElement.style.display = 'none', 300);
        }
    } catch (error) {
        console.error('加载用户信息失败:', error);
    }
}

function showFriendCodeDialog() {
    const dialog = document.getElementById('friendCodeDialog');
    dialog.classList.add('show');
}

function closeFriendCodeDialog() {
    const dialog = document.getElementById('friendCodeDialog');
    dialog.classList.remove('show');
    document.getElementById('friendCode').value = '';
}

async function performQuery(userId, selectedType, longId, friendCode = null) {
    if (isQuerying) return;
    
    isQuerying = true;
    const queryButton = document.getElementById('queryButton');
    const originalText = queryButton.textContent;
    queryButton.textContent = '查询中...';

    try {
        let result;
        if (selectedType === 'cn') {
            // 使用表单提交到响应处理页面
            result = await new Promise((resolve, reject) => {
                // 创建一个隐藏的表单
                const form = document.createElement('form');
                form.method = 'GET';
                form.action = 'response.html';
                form.target = '_blank';
                form.style.display = 'none';

                // 添加参数
                const params = {
                    api: CN_API_URL,
                    key: CN_API_KEY,
                    uid: friendCode || longId,
                    gy: 'gf'
                };

                Object.entries(params).forEach(([key, value]) => {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = key;
                    input.value = value;
                    form.appendChild(input);
                });

                // 添加到页面
                document.body.appendChild(form);

                // 创建一个新窗口
                const newWindow = window.open('about:blank', '_blank', 'width=1,height=1');
                if (!newWindow) {
                    reject(new Error('请允许弹出窗口'));
                    return;
                }

                // 监听新窗口的加载完成事件
                const checkWindow = setInterval(() => {
                    if (newWindow.closed) {
                        clearInterval(checkWindow);
                        try {
                            // 尝试从 localStorage 获取数据
                            const responseData = localStorage.getItem('tempResponse');
                            if (responseData) {
                                localStorage.removeItem('tempResponse');
                                const data = JSON.parse(responseData);
                                
                                // 检查是否是错误响应
                                if (data.code === 500) {
                                    reject(new Error(data.msg || '请求失败'));
                                    return;
                                }
                                
                                resolve(data);
                            } else if (!friendCode && responseData && responseData.includes('好友邀请码')) {
                                // 如果响应中包含"好友邀请码"字样，说明需要好友码
                                resolve({
                                    code: 401,
                                    msg: "首次查询身高时需要输入好友邀请码, 请前往游戏内创建好友邀请码并重新查询身高!",
                                    num: 0
                                });
                            } else {
                                reject(new Error('获取数据失败'));
                            }
                        } catch (error) {
                            console.error('解析响应失败:', error, responseData);
                            reject(new Error('解析响应失败'));
                        }
                    }
                }, 100);

                // 提交表单
                form.submit();

                // 添加超时处理
                setTimeout(() => {
                    clearInterval(checkWindow);
                    if (!newWindow.closed) {
                        newWindow.close();
                    }
                    reject(new Error('请求超时'));
                }, 10000);

                // 清理表单
                setTimeout(() => {
                    document.body.removeChild(form);
                }, 1000);
            });
            
            if (result.code === 401 || result.code === 402) {
                pendingQueryData = { userId, selectedType, longId };
                showFriendCodeDialog();
                showSnackbar(result.msg);
                return;
            }
        } else {
            const apiType = selectedType === 'live' ? 'gjf' : 'csf';
            const response = await fetch(`${API_BASE_URL}/${apiType}?key=${API_KEY}&id=${longId}`, {
                method: 'GET',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            result = await response.json();
        }

        if (result?.code === 200) {
            const data = result.data || result;
            const resultHtml = formatResult(result);
            document.querySelector('.result-content').innerHTML = resultHtml;
            document.getElementById('resultPopup').classList.add('show');
            
            // 保存历史记录
            await saveHistory({
                id: longId,
                type: selectedType,
                queryUserId: userId,
                timestamp: Date.now(),
                data: result
            });
        } else {
            showSnackbar(result?.msg || '查询失败，请稍后重试');
        }
    } catch (error) {
        console.error('查询失败:', error);
        showSnackbar('查询失败，请稍后重试');
    } finally {
        isQuerying = false;
        queryButton.textContent = originalText;
    }
}

// 绑定事件监听器
function bindEventListeners() {
    // 服务器选择按钮
    const serverButtons = document.getElementById('serverButtons');
    serverButtons.addEventListener('click', function(e) {
        if (e.target.classList.contains('server-button')) {
            document.querySelectorAll('.server-button').forEach(btn => btn.classList.remove('active'));
            e.target.classList.add('active');
            currentServer = e.target.dataset.type;
        }
    });

    // 好友码对话框关闭按钮
    document.querySelector('#friendCodeDialog .dialog-close').addEventListener('click', closeFriendCodeDialog);

    // 好友码提交按钮
    document.getElementById('submitFriendCode').addEventListener('click', async function() {
        const friendCode = document.getElementById('friendCode').value.trim();
        if (!friendCode) {
            showSnackbar('请输入好友码');
            return;
        }

        if (pendingQueryData) {
            closeFriendCodeDialog();
            await performQuery(pendingQueryData.userId, pendingQueryData.selectedType, pendingQueryData.longId, friendCode);
            pendingQueryData = null;
        }
    });

    // 查询按钮
    document.getElementById('queryButton').addEventListener('click', queryHeight);

    // 帮助按钮
    document.getElementById('userIdHelp').addEventListener('click', function() {
        document.getElementById('userIdTutorial').classList.add('show');
    });

    document.getElementById('accountIdHelp').addEventListener('click', function() {
        document.getElementById('accountIdTutorial').classList.add('show');
    });

    // 关闭教程对话框
    document.querySelectorAll('.dialog-close').forEach(button => {
        button.addEventListener('click', function() {
            this.closest('.tutorial-dialog').classList.remove('show');
        });
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async () => {
    try {
        // 初始化 COS 对象
        const cos = new COS({
            SecretId: 'AKID590d4KNEvQvY6Zu43qbBamkX9anmY9Xi',
            SecretKey: '2qQn4G8yjJhtttshWTGzdEvbFm8NSPDp'
        });

        // 初始化 cosHandler
        cosHandler = new CosHandler(cos);
        
        // 绑定事件监听器
        bindEventListeners();
        
        // 加载历史记录
        await loadHistory();
        
        // 加载公告
        await loadAnnouncement();
    } catch (error) {
        console.error('初始化失败:', error);
        showSnackbar('初始化失败，请刷新页面重试');
    }
});

async function loadHistory() {
    try {
        const history = await cosHandler.getHistory();
        const historyList = document.getElementById('historyList');
        if (!historyList) return;

        if (!history || history.length === 0) {
            historyList.innerHTML = '<div class="empty-state">暂无历史记录</div>';
            return;
        }

        historyList.innerHTML = history.map(item => renderHistoryItem(item)).join('');
    } catch (error) {
        console.error('加载历史记录失败:', error);
        const historyList = document.getElementById('historyList');
        if (historyList) {
            historyList.innerHTML = '<div class="empty-state">加载历史记录失败，请刷新重试</div>';
        }
    }
} 